package com.congee02.aop.proxy.dynamic;

import java.lang.reflect.Proxy;

/**
 * @author congee(congee02 @ 163.com)
 * @date 1/26/2023 11:35 AM
 */
public class BasicDynamicProxyFactory implements DynamicProxyFactory {

    private final Execution before;
    private final Object target;
    private final Execution after;

    public BasicDynamicProxyFactory(Execution before, Object target, Execution after) {
        this.before = before;
        this.target = target;
        this.after = after;
    }

    public Object getProxyInstance() {
        Class<?> clazz = target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(),
            (proxy, method, args) -> {
                before.execute();
                Object retValue = method.invoke(target, args);
                after.execute();
                return retValue;
            });
    }
}
